package com.example.web.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.domain.Point;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.ResponsePath;
import com.graphhopper.config.CHProfile;
import com.graphhopper.config.Profile;
import com.graphhopper.util.*;
import com.graphhopper.util.shapes.GHPoint;
import org.springframework.web.bind.annotation.*;
import java.io.FileNotFoundException;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/map_test")
public class MapT {

    @PostMapping("/way")
    public static JSONObject list(@RequestBody Point point) throws FileNotFoundException {
        GraphHopper hopper = new GraphHopper();
        // OSM 文件路径
        hopper.setOSMFile("E:\\osm\\gem.osm");
        // 读取完OSM数据之后会构建路线图，此处配置图的存储路径
        hopper.setGraphHopperLocation("resources");
        // 支持car、bike、foot三种交通方式的导航
        hopper.setProfiles(new Profile("car").setWeighting("fastest").setTurnCosts(false));
        //设置汽车
        hopper.getCHPreparationHandler().setCHProfiles(new CHProfile("car"));
        // 加载地图数据
        hopper.importOrLoad();

        double distance = 0;
        long timeInMs = 0;
        JSONArray pathWay = new JSONArray();

        // 对多途径点分别两两分组规划路径
        for (int i = 1; i < point.getPathWay().length; i++) {
            double[] p = point.getPathWay()[i-1];
            double[] p2 = point.getPathWay()[i];
            if(i==1)
                pathWay.add(p);

            double startLat = p[1];
            double startLng = p[0];
            double endLat = p2[1];
            double endLng = p2[0];

            GHRequest req = new GHRequest(startLat, startLng, endLat, endLng)
                    .setProfile("car");
            GHResponse rsp = hopper.route(req);

            // 报错处理
            if (rsp.hasErrors())
                throw new RuntimeException(rsp.getErrors().toString());

            // 使用最佳路径，请参阅GHResponse类以了解更多可能性。
            ResponsePath path = rsp.getBest();
            PointList pointList = path.getPoints();
            for (int j = 0; j < pointList.size(); ++j) {
                JSONArray ja = new JSONArray();
                ja.add(pointList.getLon(j)+0.001);
                ja.add(pointList.getLat(j)-0.0004);
                pathWay.add(ja);
            }

            // 对两两分组的规划结果进行保存
            pathWay.add(p2);
            distance += path.getDistance();
            timeInMs += path.getTime();
        }

        // 返回最终结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("distance",distance+"米");
        jsonObject.put("time",timeInMs+"毫秒");
        jsonObject.put("path",pathWay);
        return jsonObject;
    }

    @GetMapping("/test2")
    public static String test2(){
        return "ok";
    }

}
